package song.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import song.demo.bean.UserBean;
import song.demo.service.UserService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    @Resource
    UserService userService;

    //getAllUser
    @RequestMapping("/users")
    public String showUsers(ModelMap modelMap){
        List<UserBean> userList = userService.getAllUser();
        for (UserBean userBeanList:userList){
            System.out.println("id:"+userBeanList.getId()+" name:"+userBeanList.getName()+" 密码:"+userBeanList.getPassword()+" 权限:"+userBeanList.getRole());
        }
        System.out.println("--------------以上是当前访问的数据----------------------");

        //log中查看:已拿到数据
        modelMap.addAttribute("userList",userList);
        return "users";
    }

    //insertUser
    @RequestMapping("/addUser")
    @ResponseBody
    public Map addUser(UserBean userBean){
        int flag = userService.insertUser(userBean);
        Map<String,Object> map = new HashMap<>();
        if(flag == 1){
            map.put("msg","添加用户成功!");
            return map;
        }else {
            map.put("msg","添加用户失败!");
            return map;
        }
    }

    //delete
    @RequestMapping(value = "/deleteUser+{id}")
    public String deleteUser(@PathVariable("id") String id,ModelMap modelMap){
        int flag = userService.deleteUser(id);
        List<UserBean> userList = userService.getAllUser();
        modelMap.addAttribute("userList",userList);
        if(flag==1){
            return "users";
        }else {
            return "error";
        }
    }

    //查找指定id用户
    @RequestMapping("/user+{id}")
    public String getUserByid(@PathVariable("id") String id,ModelMap modelMap){
        UserBean userBean = userService.getUserById(id);
        modelMap.addAttribute("user",userBean);
        return "userInfo";
    }

    //修改指定用户信息
    @RequestMapping("/modifyUser")
    @ResponseBody
    public Map updateUser(UserBean userBean){
        int flag = userService.updateUser(userBean);
        Map<String,Object> map = new HashMap<>();
        if (flag==1){
            map.put("msg","修改用户信息成功!");
            return map;
        }else {
            map.put("msg","修改用户信息失败!");
            return map;
        }
    }
}
